package com.zhongcw.test.java.md5.AES;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import java.security.SecureRandom;
import java.util.Arrays;

public class AES {
    public static void main(String[] args) throws Exception {
        KeyGenerator keygen;
        SecretKey aeskey;
        Cipher c;

        keygen = KeyGenerator.getInstance("AES");
        aeskey = keygen.generateKey();
        c = Cipher.getInstance("AES/CBC/PKCS5Padding");

        SecureRandom rnd = new SecureRandom();
        IvParameterSpec iv = new IvParameterSpec(rnd.generateSeed(16));

        String msg = "hello world";
        System.out.println("明文：" + msg);

        c.init(Cipher.ENCRYPT_MODE, aeskey, iv);
        byte[] src = msg.getBytes();
        byte[] enc = c.doFinal(src);
        System.out.println("密文：" + Arrays.toString(enc));

        //
        StringBuffer md5str = new StringBuffer();

        // 把数组每一字节换成16进制连成md5字符串
        int digital;
        int len = enc.length;
        for (int i = 0; i < len; i++) {
            digital = enc[i];

            if (digital < 0) {
                digital += 256;
            }
            if (digital < 16) {
                md5str.append("0");
            }
            md5str.append(Integer.toHexString(digital));
        }

        System.out.println("密文：" + md5str.toString().toUpperCase());

        //

        c.init(Cipher.DECRYPT_MODE, aeskey, iv);
        byte[] dec = c.doFinal(enc);
    }
}